import os
from string import Template
import yaml
from Base.baseContainer import GlobalManager
from Base.baseLogger import Logger
from Base.basePath import BasePath as BP
from Base.utils import read_config_ini
from Base.baseYaml import read_yaml
from Base.baseExcel import ExcelRead

logger = Logger('baseData.py').getLogger()


def init_file_path(pic_path):
    """遍历目录下所有文件的路径"""
    path = {}
    path_lists = [path_list for path_list in os.walk(pic_path)]
    for file_tup in path_lists:
        for file_path in file_tup:
            if isinstance(file_path, str):
                value = file_path
            elif isinstance(file_path, list):
                for file_name in file_path:
                    path[file_name.split('.')[0]] = os.path.join(value,file_name)
    return path


def is_file_exist(file_path,yamlName):
    """检查json中读取的图片名称获取全路径后是否存在"""
    abs_path = file_path.get(yamlName)
    if not abs_path:
        pass
        # raise FileNotFoundError('el:{} 不存在检查文件名或检查配置文件TEST_PROJECT！'.format(yamlName))
    return abs_path


class DataBase():
    '''读取数据'''


    def __init__(self,yamlName=None):
        self.gm = GlobalManager()
        self.yamlName = yamlName
        self.config = read_config_ini(BP.CONFIG_FILE)
        self.run_config = self.config['项目运行设置']
        # self.aa = os.path.join(BP.DATA_ELEMENT_DIR,self.run_config['TEST_PROJECT'])
        # print(self.aa)
        # self.api_path = init_file_path(os.path.join(BP.DATA_ELEMENT_DIR,self.run_config['TEST_PROJECT']))
        # print(self.api_path)
        self.api_path = init_file_path(r'C:\Users\10447\PycharmProjects\podemo_001\Data\DataaElement\test1')
        if not self.run_config['AUTO_TYPE'] == 'CLIENT':
            self.abs_path = is_file_exist(self.api_path,self.yamlName)

    def get_element_data(self, change_data=None):
        '''动态替换yaml中的值，返回替换后的内容'''
        if change_data:
            with open(self.abs_path, 'r', encoding='utf-8') as f:
                cfg = f.read()
                content = Template(cfg).safe_substitute(**change_data)
                return yaml.load(content, Loader=yaml.FullLoader)
        else:
            return read_yaml(self.abs_path)


class DataDriver():
    '''读取数据'''

    def __init__(self):
        self.gm = GlobalManager()
        self.config = read_config_ini(BP.CONFIG_FILE)

    def get_case_data(self,yamlName):
        '''获取数据驱动'''
        data_type = self.config['项目运行设置']['DATA_DRIVER_TYPE']
        abs_path = init_file_path(os.path.join(BP.DATA_DRIVER_DIR,data_type,self.config['项目运行设置']['TEST_PROJECT']))
        print(abs_path)
        data_path = is_file_exist(abs_path,yamlName)
        if data_type == 'YamlDriver':
            return read_yaml(data_path)
        elif data_type == 'ExcelDriver':
            return ExcelRead(data_path).dict_date()


if __name__ == '__main__':
    # ele = DataBase('接口元素信息')
    # change_data = {
    #     "test": "1",
    #     "user":"guang"
    # }
    # res = ele.get_element_data(change_data)
    # print(res)
    # print('*************')
    driver = DataDriver()
    res = driver.get_case_data('vip模板下载.xls')
    print(res)


    # res = init_file_path(r'C:\Users\10447\PycharmProjects\podemo_001\Data\DataaElement\test1')
    # print(res)



